package ch09;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Statement;

public class MessageDAO {

	private String url;
	private String user;
	private String passwd;
	
	public MessageDAO(String url,String user,String passwd){
		this.url = url;
		this.user = user;
		this.passwd = passwd;
	}
	
	public void add(Message message) throws SQLException {
		try(Connection conn = DriverManager.getConnection(url,user,passwd);
				Statement statement = (Statement) conn.createStatement()){
			String sql = String.format(
					"INSERT INTO t_message(name,email,msg) VALUES ('%s','%s','%s')", 
					message.getName(),message.getEmail(),message.getMsg());
			statement.executeUpdate(sql);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public List<Message> get() {
		List<Message> messages = new ArrayList();
		
		try(Connection conn = DriverManager.getConnection(url,user,passwd);
				Statement statement = (Statement) conn.createStatement()){
			ResultSet result = statement.executeQuery("SELECT * FROM t_message");
			while(result.next()){
				Message message = toMessage(result);
				messages.add(message);
			}
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return messages;
	}

	public Message toMessage(ResultSet result) throws SQLException {
		Message message = new Message();
		message.setId(result.getLong(1));
		message.setName(result.getString(2));
		message.setEmail(result.getString(3));
		message.setMsg(result.getString(4));
		return message;
	}
}
